package com.example.blog.admin;

import com.example.blog.pojo.Blog;
import com.example.blog.MyDBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.UUID;

@WebServlet("/admin-blog-edit")
@MultipartConfig
public class BlogEditServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String idStr = request.getParameter("id");
        if (idStr == null || idStr.trim().isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/admin-blog-list");
            return;
        }

        try {
            int id = Integer.parseInt(idStr);
            Blog blog = getBlogById(id);

            if (blog == null) {
                response.sendRedirect(request.getContextPath() + "/admin-blog-list");
                return;
            }

            request.setAttribute("blog", blog);
            request.getRequestDispatcher("/WEB-INF/admin/blog-edit.jsp").forward(request, response);

        } catch (NumberFormatException e) {
            response.sendRedirect(request.getContextPath() + "/admin-blog-list");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");

        // 要上传到哪里
        String uploadPath = getServletContext().getRealPath("/") + "uploads";

        // 处理文件上传 - start
        Part filePart = request.getPart("cover");
        String coverFileName = null;

        // 判断用户有没有上传封面图
        if (filePart != null && filePart.getSize() > 0) {
            // 获取原始文件名和扩展名
            String originalFileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
            String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));

            // 生成新的文件名：时间戳_UUID.扩展名
            String newFileName = System.currentTimeMillis() + "_" +
                    UUID.randomUUID().toString().substring(0, 8) +
                    fileExtension;

            // 检查 uploads 文件夹是否存在，如果不存在，自动创建
            Path uploadsPath = Paths.get(uploadPath);
            if (!Files.exists(uploadsPath)) {
                Files.createDirectories(uploadsPath);
            }

            // 使用新文件名保存文件
            File uploadedFile = new File(uploadPath, newFileName);
            filePart.write(uploadedFile.getAbsolutePath());
            coverFileName = "uploads/" + newFileName;

            // 如果是更新操作，删除旧的封面图
            Blog oldBlog = getBlogById(Integer.parseInt(request.getParameter("id")));
            if (oldBlog != null && oldBlog.getCover() != null) {
                File oldCover = new File(getServletContext().getRealPath("/") + oldBlog.getCover());
                if (oldCover.exists()) {
                    oldCover.delete();
                }
            }
        }
        // 处理文件上传 - end

        String idStr = request.getParameter("id");
        String title = request.getParameter("title");
        String content = request.getParameter("content");

        if (idStr == null || title == null || content == null ||
                title.trim().isEmpty() || content.trim().isEmpty()) {
            response.sendRedirect(request.getContextPath() + "/admin-blog-list");
            return;
        }

        try {
            int id = Integer.parseInt(idStr);
            updateBlog(id, title, content, coverFileName);
            response.sendRedirect(request.getContextPath() + "/admin-blog-list");

        } catch (NumberFormatException e) {
            response.sendRedirect(request.getContextPath() + "/admin-blog-list");
        }
    }

    private Blog getBlogById(int id) throws ServletException {
        try (Connection conn = MyDBUtil.getConnection()) {
            String sql = "SELECT id, title, content, cover FROM blog WHERE id = ?";
            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                stmt.setInt(1, id);
                ResultSet rs = stmt.executeQuery();

                if (rs.next()) {
                    Blog blog = new Blog();
                    blog.setId(rs.getInt("id"));
                    blog.setTitle(rs.getString("title"));
                    blog.setContent(rs.getString("content"));
                    blog.setCover(rs.getString("cover"));
                    return blog;
                }
            }
        } catch (SQLException e) {
            throw new ServletException("获取博客信息失败", e);
        }
        return null;
    }

    private void updateBlog(int id, String title, String content, String coverFileName) throws ServletException {
        try (Connection conn = MyDBUtil.getConnection()) {
            String sql;
            if (coverFileName != null) {
                sql = "UPDATE blog SET title = ?, content = ?, cover = ? WHERE id = ?";
            } else {
                sql = "UPDATE blog SET title = ?, content = ? WHERE id = ?";
            }

            try (PreparedStatement stmt = conn.prepareStatement(sql)) {
                stmt.setString(1, title);
                stmt.setString(2, content);
                if (coverFileName != null) {
                    stmt.setString(3, coverFileName);
                    stmt.setInt(4, id);
                } else {
                    stmt.setInt(3, id);
                }
                stmt.executeUpdate();
            }
        } catch (SQLException e) {
            throw new ServletException("更新博客失败", e);
        }
    }
}